"""
工作流管理服务
"""
from typing import List, Optional, Tuple
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.models.hiagent_models import (
    Workflow, WorkflowInputSchema, ListOption
)


class WorkflowService:
    """工作流服务类"""

    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()

    def list_workflows(
        self,
        list_opt: Optional[ListOption] = None,
        workspace_id: Optional[str] = None,
        keyword: Optional[str] = None,
        status: Optional[str] = None
    ) -> Tuple[List[Workflow], int]:
        """获取工作流列表

        Args:
            list_opt: 分页选项
            workspace_id: 工作空间ID
            keyword: 关键词搜索
            status: 工作流状态 (Published/Unpublished)

        Returns:
            (工作流列表, 总数)
        """
        body = {
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        # 设置分页参数 - 根据HiAgent API文档,使用PageNumber而不是Page
        if list_opt:
            list_opt_dict = {}
            if list_opt.page is not None:
                list_opt_dict["PageNumber"] = list_opt.page  # 修改: Page -> PageNumber
            if list_opt.page_size is not None:
                list_opt_dict["PageSize"] = list_opt.page_size
            if list_opt.sort_field:
                list_opt_dict["SortField"] = list_opt.sort_field
            if list_opt.sort_order:
                list_opt_dict["SortOrder"] = list_opt.sort_order

            if list_opt_dict:
                body["ListOpt"] = list_opt_dict

        # 设置筛选条件
        filter_dict = {}
        if keyword:
            filter_dict["Keyword"] = keyword
        if status:
            filter_dict["Status"] = status

        if filter_dict:
            body["Filter"] = filter_dict

        try:
            response = self.api_client.make_request("ListWorkflows", body)

            workflows = []
            for item in response.get("Items", []):
                # 解析输入参数schema
                input_schema = []
                for schema_item in item.get("InputSchema", []):
                    input_schema.append(WorkflowInputSchema(
                        name=schema_item.get("Name", ""),
                        desc=schema_item.get("Desc", ""),
                        type=schema_item.get("Type", 0),
                        required=schema_item.get("Required"),
                        default=schema_item.get("Default")
                    ))

                workflows.append(Workflow(
                    workflow_id=item.get("ID", ""),
                    name=item.get("Name", ""),
                    description=item.get("Description", ""),
                    status=item.get("Status"),
                    runtime_status=item.get("RuntimeStatus"),
                    input_schema=input_schema if input_schema else None,
                    icon=item.get("Icon"),
                    dirty=item.get("Dirty"),
                    create_time=item.get("CreateTime"),
                    create_user=item.get("CreateUser"),
                    update_time=item.get("UpdateTime"),
                    update_user=item.get("UpdateUser"),
                    workspace_id=item.get("WorkspaceID")
                ))

            total = response.get("Total", 0)
            return workflows, total

        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"ListWorkflows failed: {str(e)}")
            return [], 0

    def get_workflow(
        self,
        workflow_id: str,
        workspace_id: Optional[str] = None
    ) -> Optional[Workflow]:
        """获取工作流详情

        Args:
            workflow_id: 工作流ID
            workspace_id: 工作空间ID

        Returns:
            工作流对象，如果不存在返回None
        """
        body = {
            "ID": workflow_id,
            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
        }

        try:
            response = self.api_client.make_request("GetWorkflow", body)

            if not response:
                return None

            # 解析输入参数schema
            input_schema = []
            for schema_item in response.get("InputSchema", []):
                input_schema.append(WorkflowInputSchema(
                    name=schema_item.get("Name", ""),
                    desc=schema_item.get("Desc", ""),
                    type=schema_item.get("Type", 0),
                    required=schema_item.get("Required"),
                    default=schema_item.get("Default")
                ))

            return Workflow(
                workflow_id=response.get("ID", ""),
                name=response.get("Name", ""),
                description=response.get("Description", ""),
                status=response.get("Status"),
                runtime_status=response.get("RuntimeStatus"),
                input_schema=input_schema if input_schema else None,
                icon=response.get("Icon"),
                dirty=response.get("Dirty"),
                create_time=response.get("CreateTime"),
                create_user=response.get("CreateUser"),
                update_time=response.get("UpdateTime"),
                update_user=response.get("UpdateUser"),
                workspace_id=response.get("WorkspaceID")
            )

        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"GetWorkflow failed: {str(e)}")
            return None

    def list_published_workflows(
        self,
        list_opt: Optional[ListOption] = None,
        workspace_id: Optional[str] = None,
        keyword: Optional[str] = None
    ) -> Tuple[List[Workflow], int]:
        """获取已发布的工作流列表

        Args:
            list_opt: 分页选项
            workspace_id: 工作空间ID
            keyword: 关键词搜索

        Returns:
            (工作流列表, 总数)
        """
        return self.list_workflows(
            list_opt=list_opt,
            workspace_id=workspace_id,
            keyword=keyword,
            status="Published"
        )
